import GeoTIFF from "ol/source/GeoTIFF";
import Map from "ol/Map.js";
import WebGLTileLayer from "ol/layer/WebGLTile";
import Tile from "ol/layer/Tile.js";
import View from "ol/View.js";
import OSM from "ol/source/OSM.js";
import GeoJSON from "ol/format/GeoJSON.js";
import VectorSource from "ol/source/Vector.js";
import {bbox as bboxStrategy} from "ol/loadingstrategy";

import VectorLayer from "ol/layer/Vector.js";
import {Fill, Stroke, Circle, Style} from "ol/style.js";

const map = new Map({
	target: "map",
	layers: [
		new Tile({
			source: new OSM(),
		}),
	],
	view: new View({
		center: [115.4169, 39.4422, 117.5082, 41.0592],
		zoom: 12,
	}),
});

const getStroke = (isFirst, color) =>
	new Stroke({
		color: isFirst ? "#000" : color,
		width: 2,
	});

const getFill = (isFirst, color) =>
	new Fill({
		color: isFirst ? "rgba(170, 170, 170, .2)" : color,
	});

/* 调用函数并获取 OpenLayers 样式数组
const SLD = `<?xml version="1.0" encoding="UTF-8"?><sld:StyledLayerDescriptor xmlns="http://www.opengis.net/sld" xmlns:sld="http://www.opengis.net/sld" xmlns:gml="http://www.opengis.net/gml" xmlns:ogc="http://www.opengis.net/ogc" version="1.0.0">
<sld:NamedLayer>
  <sld:Name>Default Styler</sld:Name>
  <sld:UserStyle>
	<sld:Name>Default Styler</sld:Name>
	<sld:Title>Generic</sld:Title>
	<sld:Abstract>Generic style</sld:Abstract>
	<sld:FeatureTypeStyle>
	  <sld:Name>name</sld:Name>
	  <sld:Rule>
		<sld:Name>raster</sld:Name>
		<sld:Title>Opaque Raster</sld:Title>
		<ogc:Filter>
		  <ogc:PropertyIsEqualTo>
			<ogc:Function name="isCoverage"/>
			<ogc:Literal>true</ogc:Literal>
		  </ogc:PropertyIsEqualTo>
		</ogc:Filter>
		<sld:RasterSymbolizer>
		  <sld:ContrastEnhancement/>
		</sld:RasterSymbolizer>
	  </sld:Rule>
	  <sld:Rule>
		<sld:Name>Polygon</sld:Name>
		<sld:Title>Grey Polygon</sld:Title>
		<ogc:Filter>
		  <ogc:PropertyIsEqualTo>
			<ogc:Function name="dimension">
			  <ogc:Function name="geometry"/>
			</ogc:Function>
			<ogc:Literal>2</ogc:Literal>
		  </ogc:PropertyIsEqualTo>
		</ogc:Filter>
		<sld:PolygonSymbolizer>
		  <sld:Fill>
			<sld:CssParameter name="fill">#00FA9A</sld:CssParameter>
			<sld:CssParameter name="fill-opacity">0.3</sld:CssParameter>
		  </sld:Fill>
		  <sld:Stroke>
			<sld:CssParameter name="stroke">#00FA9A</sld:CssParameter>
		  </sld:Stroke>
		</sld:PolygonSymbolizer>
	  </sld:Rule>
	  <sld:Rule>
		<sld:Name>Line</sld:Name>
		<sld:Title>Blue Line</sld:Title>
		<ogc:Filter>
		  <ogc:PropertyIsEqualTo>
			<ogc:Function name="dimension">
			  <ogc:Function name="geometry"/>
			</ogc:Function>
			<ogc:Literal>1</ogc:Literal>
		  </ogc:PropertyIsEqualTo>
		</ogc:Filter>
		<sld:LineSymbolizer>
		  <sld:Stroke>
			<sld:CssParameter name="stroke">#0000FF</sld:CssParameter>
		  </sld:Stroke>
		</sld:LineSymbolizer>
	  </sld:Rule>
	  <sld:Rule>
		<sld:Name>point</sld:Name>
		<sld:Title>Red Square Point</sld:Title>
		<sld:ElseFilter/>
		<sld:PointSymbolizer>
		  <sld:Graphic>
			<sld:Mark>
			  <sld:Fill>
				<sld:CssParameter name="fill">#FF0000</sld:CssParameter>
			  </sld:Fill>
			</sld:Mark>
			<sld:Size>6</sld:Size>
		  </sld:Graphic>
		</sld:PointSymbolizer>
	  </sld:Rule>
	  <sld:VendorOption name="ruleEvaluation">first</sld:VendorOption>
	</sld:FeatureTypeStyle>
  </sld:UserStyle>
</sld:NamedLayer>
</sld:StyledLayerDescriptor>
`;

// 解析SLD XML字符串
var parser = new DOMParser();
var sldXml = SLD; // 替换为你的SLD XML字符串
var sldDoc = parser.parseFromString(sldXml, "application/xml");
console.log("---->", sldDoc);
// 获取PolygonSymbolizer、LineSymbolizer和PointSymbolizer的样式规则
var polygonRule = sldDoc.querySelector('Rule[Name="Polygon"]');
var lineRule = sldDoc.querySelector('Rule[Name="Line"]');
var pointRule = sldDoc.querySelector('Rule[Name="point"]');

if (pointRule) {
	// 转换样式规则为OpenLayers样式
	var polygonStyle = new Style({
		fill: new Fill({
			color: polygonRule.querySelector('CssParameter[name="fill"]').textContent,
			opacity: parseFloat(polygonRule.querySelector('CssParameter[name="fill-opacity"]').textContent),
		}),
		stroke: new Stroke({
			color: polygonRule.querySelector('CssParameter[name="stroke"]').textContent,
		}),
	});
}

if (lineRule) {
	var lineStyle = new Style({
		stroke: new Stroke({
			color: lineRule.querySelector('CssParameter[name="stroke"]').textContent,
		}),
	});
}

if (pointRule) {
	var pointStyle = new Style({
		image: new Circle({
			radius: parseFloat(pointRule.querySelector("Size").textContent),
			fill: new Fill({
				color: pointRule.querySelector('CssParameter[name="fill"]').textContent,
			}),
		}),
	});
}
 */

// 创建样式函数，根据要素的几何类型应用相应的样式
const styleFunction = (feature, isFirst) => {
	const geometryType = feature.getGeometry().getType();
	let style = {};
	switch (geometryType) {
		case "LineString":
		case "GeometryCollection":
		case "MultiLineString":
			style = {stroke: getStroke(isFirst, "#0000ff")};
			break;
		case "MultiPoint":
		case "Point":
			style = {
				// Feature类型数据的展示
				image: new Circle({
					fill: getFill(isFirst, "#ff0000"),
					stroke: getStroke(isFirst, "#ff0000"),
					radius: 5,
				}),
			};
			break;
		case "Polygon":
		case "MultiPolygon":
			style = {
				stroke: getStroke(isFirst, "#00fa9a"),
				fill: getFill(isFirst, "#00fa9a30"),
			};
			break;
		default:
	}

	return new Style({
		...style,
	});
};

const vectorSource = new VectorSource({
	format: new GeoJSON(),
	url: "http://127.0.0.1:5173/static/json/wps_output.json",
	/* 
		loader: function (extent, resolution, projection, success = () => {}, failure = () => {}) {
			const url = "http://127.0.0.1:5173/static/json/wps_output.json";
			const xhr = new XMLHttpRequest();
			xhr.open("GET", url);
			const onError = function () {
				vectorSource.removeLoadedExtent(extent);
				failure();
			};
			xhr.onerror = onError;
			xhr.onload = function () {
				if (xhr.status === 200) {
					const features = vectorSource.getFormat().readFeatures(xhr.responseText);
					vectorSource.addFeatures(features);
					success(features);
				} else {
					onError();
				}
			};
			xhr.send();
		}, 
	*/
	strategy: bboxStrategy,
});

const wfsLayer = new VectorLayer({
	source: vectorSource,
	style: feature => styleFunction(feature, true),
});

map.addLayer(wfsLayer);
map.setView(
	new View({
		center: [470270.1, 283370.8, 563824.6, 349638.9],
		zoom: 10,
	})
);

// GEOTIFF 预览
/* const source = new GeoTIFF({
	normalize: false,
	sources: [{url: "http://127.0.0.1:5173/static/tiff/no-overviews.tif"}],
	transition: 2,
	interpolate: true,
});

const style = {
	color: [
		"case",
		["==", ["band", 1], 0],
		"hsla(240, 100%, 50%, 0)", // Blue for value 0
		["<=", ["band", 1], 0.02],
		"hsla(180, 100%, 75%, 0)", // Light Blue for values <= 0.02
		["<=", ["band", 1], 0.1],
		"hsla(120, 100%, 50%, 1)", // Green for values <= 0.1
		["<=", ["band", 1], 0.5],
		"hsla(60, 100%, 75%, 1)", // Yellow for values <= 0.5
		"hsla(0, 100%, 50%, 1)", // Default Red color
	],
};

const layer = new WebGLTileLayer({
	// style: style,
	source: source,
	opacity: 0.5,
});

map.addLayer(layer);

map.setView(source.getView()); */
